package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.dto.OrdersDto;
import com.itheima.entity.*;
import com.itheima.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @PackageName: com.itheima.controller
 * @ClassName: OrdersController
 * @Description:
 * @Author: zhangcheng
 * @DateTime: 2022/6/13 10:23
 * @Version 1.0
 */

@RestController
@RequestMapping("/order")
@Transactional
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 下单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        //查询当前用户购物车信息
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(
                new LambdaQueryWrapper<ShoppingCart>()
                        .eq(ShoppingCart::getUserId, BaseContext.getCurrentId()));
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            return R.error("购物车为空,不能下单");
        }
        //用户信息
        User user = userService.getById(BaseContext.getCurrentId());
        //地址信息
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if (addressBook == null) {
            return R.error("收货地址有误,不能下单");
        }
        long orderId = IdWorker.getId();//订单号
        AtomicInteger amount = new AtomicInteger(0);//总价
        // 保存订单明细数据：点了哪些菜品或套餐
        List<OrderDetail> orderDetailList = shoppingCartList.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(item, orderDetail);
            //单独设置订单号
            orderDetail.setOrderId(orderId);
            //amount 数量*单价
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        orderDetailService.saveBatch(orderDetailList);
        // 保存订单数据 , 需要单独设置
        orders.setNumber(String.valueOf(orderId));
        orders.setStatus(2);//1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(BaseContext.getCurrentId());//用户id
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setNumber(String.valueOf(orderId));//订单号
        orders.setUserName(user.getName());//用户名
        orders.setConsignee(addressBook.getConsignee());//收货人
        orders.setPhone(addressBook.getPhone());//收货人联系电话
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));//省+市+区域+详细地址
        ordersService.save(orders);
        //下单成功,删除当前用户的购物车数据
        shoppingCartService.remove(new LambdaQueryWrapper<ShoppingCart>()
                .eq(ShoppingCart::getUserId, BaseContext.getCurrentId()));
        return R.success("下单成功");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R page(Integer page, Integer pageSize) {
        IPage<Orders> pageInfo = new Page<>(page, pageSize);
        ordersService.page(pageInfo, new LambdaQueryWrapper<Orders>()
                .eq(Orders::getUserId, BaseContext.getCurrentId())
                .orderByDesc(Orders::getCheckoutTime));

        List<OrdersDto> ordersDtos = pageInfo.getRecords().stream().map((item) -> {
            List<OrderDetail> list = orderDetailService.list(
                    new LambdaQueryWrapper<OrderDetail>()
                            .eq(OrderDetail::getOrderId, item.getId()));
            OrdersDto ordersDto = new OrdersDto();
            ordersDto.setOrderDetails(list);
            BeanUtils.copyProperties(item, ordersDto);
            return ordersDto;
        }).collect(Collectors.toList());
        Map<String, Object> data = new HashMap<>();
        data.put("records", ordersDtos);
        data.put("total", (int) pageInfo.getTotal());
        return R.success(data);
    }

    /**
     * 后台分页查询所有订单
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R pages(Integer page, Integer pageSize, String number, String beginTime, String endTime) {
        IPage<Orders> pageInfo = new Page<>(page, pageSize);
        ordersService.page(pageInfo, new LambdaQueryWrapper<Orders>()
                .ge(StringUtils.isNotBlank(beginTime), Orders::getOrderTime, beginTime)
                .le(StringUtils.isNotBlank(endTime), Orders::getCheckoutTime, endTime)
                .like(StringUtils.isNotBlank(number), Orders::getNumber, number)
                .orderByDesc(Orders::getCheckoutTime));
        return R.success(pageInfo);
    }

    @PutMapping
    public R status(@RequestBody Orders orders) {
        if (orders.getStatus()==3) {
            ordersService.update(new LambdaUpdateWrapper<Orders>()
                    .set(Orders::getStatus, 3)
                    .eq(Orders::getId, orders.getId()));
        }else if (orders.getStatus()==4){
            ordersService.update(new LambdaUpdateWrapper<Orders>()
                    .set(Orders::getStatus, 4)
                    .eq(Orders::getId, orders.getId()));
        }
        return R.success(null);
    }
}
